import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import MyView from '../views/MyView.vue'
import SignupView from '../views/SignupView.vue'
import CourseSelectView from "@/views/CourseSelectView.vue";
import CourseShowView from "@/views/CourseShowView.vue";
import UserUpdata from "@/views/UserUpdata.vue";


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        login_required:true
      }
    },
    {
      path: '/my',
      name: 'my',
      component: MyView,
      meta: {
        login_required:true
      }
    },
    {
      path: '/course_select',
      name: 'course_select',
      component: CourseSelectView,
      meta: {
        login_required:true
      }
    },
    {
      path: '/course_show',
      name: 'course_show',
      component: CourseShowView,
      meta: {
        login_required:true
      }
    },
    {
      path: '/user_updata',
      name: 'user_updata',
      component: UserUpdata,
      meta: {
        login_required:true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/signup',
      name: 'signup',
      component: SignupView
    }
  ]
})

router.beforeEach((to, from, next) => {
  let logged_in = false
  if(sessionStorage.token) {
    logged_in = true
  }

  if(!logged_in && to.matched.some((item)=>{
    return item.meta.login_required
  })){
    next('/login')
  } else {
    next()
  }
})

export default router